package com.jd.org.controller;

import com.jd.basic.util.AjaxResult;
import com.jd.basic.util.PageList;
import com.jd.org.domain.Department;
import com.jd.org.query.DepartmentQuery;
import com.jd.org.service.IDepartmentService;
import com.jd.system.annotation.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Api(value = "部门的接口类",description = "部门的接口类")
@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    // 查询id
    @ApiOperation(value = "查询单个")
    @GetMapping("/{id}")
    public Department findOne(@PathVariable("id")Long id){
        return departmentService.loadById(id);
    }


    // 查询全部
    @ApiOperation(value = "查询全部")
    @GetMapping
    public List<Department> findAll (){
        return departmentService.loadAll();
    }

    // 删除
    @ApiOperation(value = "查询删除")
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "部门的删除",sn = "department:delete")
    public AjaxResult remove(@PathVariable("id")Long id){
        try {
            departmentService.remove(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败啦");
        }
    }

    // 添加修改和增加
    @ApiOperation(value = "查询修改和增加")
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if (department.getId()== null){
                departmentService.save(department);
            } else {
                departmentService.update(department);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }

    // 分页
    @ApiOperation(value = "查询分页")
    @PostMapping
    @PreAuthorize(name = "部门分页",sn = "department:list")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){

        return departmentService.queryPage(departmentQuery);
    }



    // 批量删除
    @ApiOperation(value = "批量删除")
    @PatchMapping
    public AjaxResult patchRemove(@RequestBody List<Long> ids){
        try {
            departmentService.patchRemove(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"批量删除失败啦");
        }
    }


    // 查询部门树
    @ApiOperation(value = "查询部门树")
    @GetMapping("/deptTree")
    public List<Department> deptTree(){
        return departmentService.deptTree();
    }




}
